package io.renren.common.weixin.payutils;

import io.renren.common.utils.HttpClient;
import io.renren.common.weixin.WeiXinAccessTokenService;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by whc on 2016/3/23.
 */
@Component
public class WXJSShare {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    //会员公众号微信appid
    @Value("${weixin.appId}")
    private String appId;
    //会员公众号微信appSecret
    @Value("${weixin.appSecret}")
    private String appSecret;

    @Autowired
    private WeiXinAccessTokenService weiXinAccessTokenService;

    /**
     * 获取jsticket
     * @return
     */
    public String getJsTicket(){
        try {
            String token = weiXinAccessTokenService.getAccessToken(appId,appSecret);
            String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi";
            String res = new HttpClient().sendPost(url, "");
            log.warn("url="+url);
            log.warn("res="+res);
            JSONObject json = JSONObject.fromObject(res);
            return json.getString("ticket");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取jsapi相关参数map
     * @param jsapi_ticket
     * @param url  调用分享js页面的地址
     * @return
     */
    public Map<String, String> getJsSignMap(String jsapi_ticket, String url) {
        //url = bathurl + url;
        Map<String, String> map = new HashMap<String, String>();

        String nonce_str = UUID.randomUUID().toString();
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String s = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
        String signature = Sha1Util.getSha1(s);

        map.put("url", url);
        map.put("appId",appId);
        map.put("jsapi_ticket", jsapi_ticket);
        map.put("nonceStr", nonce_str);
        map.put("timestamp", timestamp);
        map.put("signature", signature);
        return map;
    }

}
